import React from 'react';
import { Table, Cascader } from 'antd';
import http from '../../utils/api';

const columns = [{
  title: '名字',
  dataIndex: 'name',
  width: '20%',
}, {
  title: '手机号',
  dataIndex: 'mobile',
  width: '20%',
}, {
  title: '是否为管理员',
  dataIndex: 'is_principal',
  render: is_principal => is_principal ? '是' : '否',
}, {
  title: '身份',
  dataIndex: 'roles',
  render: roles => roles.join(','),
}
];

class List extends React.Component {
  state = {
    data: [],
    pagination: { pageSize: 15 },
    loading: false,
    classes: [],
  };
  handleSearchSubmit = (value = []) => {
    if (value.length === 2) {
      this.fetch({ classes_id: value[1], pagination: { pageSize: 15 } });
    }
  }
  handleTableChange = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
    console.log(pagination);
    this.fetch({
      results: pagination.pageSize,
      page: pagination.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });

    http.get('/teacher/teacher', params, data => {
      this.setState({
        loading: false,
        data: data.data,
        pagination: { total: data.total, page: data.current_page }
      });
      if (!this.state.classes.length) {
        http.get('/teacher/classes/by_grade', {}, data => {
          this.setState(
            {
              classes:
                data.map(
                  grade => (
                    { value: grade.grade_id, label: grade.grade_name, children: grade.classes.map(classes => ({ value: classes.id, label: classes.name })) }
                  )
                )
            }

          )
        });
      }
    });

  }
  componentDidMount() {
    this.fetch();
  }
  render() {
    return (
      <React.Fragment>

        <Cascader options={this.state.classes} onChange={this.handleSearchSubmit} />

        <Table columns={columns}
          rowKey={record => record.id}
          dataSource={this.state.data}
          pagination={this.state.pagination}
          loading={this.state.loading}
          onChange={this.handleTableChange}
          size='small'
        />
      </React.Fragment>
    );
  }
}

export default List;